﻿using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Star.Tools.Excel.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Star.Tools.Excel
{
    public static class WorkbookExtend
    {
        #region 将生成的Excel的文件信息【右键文件信息】
        public static void SetExcelAttributes(this HSSFWorkbook workbook, ExcelInformation excelAttribute)
        {
            if (!string.IsNullOrEmpty(excelAttribute.Company))
            {
                DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = excelAttribute.Company;
                workbook.DocumentSummaryInformation = dsi;
            }

            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            if (!string.IsNullOrEmpty(excelAttribute.Title))
                si.Title = excelAttribute.Title;
            if (!string.IsNullOrEmpty(excelAttribute.Author))
                si.Author = excelAttribute.Author;
            if (!string.IsNullOrEmpty(excelAttribute.Subject))
                si.Subject = excelAttribute.Subject;
            if (!string.IsNullOrEmpty(excelAttribute.Comments))
                si.Comments = excelAttribute.Comments;
            if (!string.IsNullOrEmpty(excelAttribute.ApplicationName))
                si.ApplicationName = excelAttribute.ApplicationName;
            si.CreateDateTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"));
            workbook.SummaryInformation = si;
        }
        public static void SetExcelAttributes(this XSSFWorkbook workbook, ExcelInformation excelAttribute)
        {
            var props = workbook.GetProperties();
            if (!string.IsNullOrEmpty(excelAttribute.Title))
                props.CoreProperties.Title = excelAttribute.Title;
          
            if (!string.IsNullOrEmpty(excelAttribute.Subject))
                props.CoreProperties.Subject = excelAttribute.Subject;

            props.ExtendedProperties.GetUnderlyingProperties().Company = excelAttribute.Company;


        }
        #endregion

        #region 将workbook转换成二进制文件流

        /// <summary>
        ///     将workbook转换成二进制文件流
        /// </summary>
        /// <param name="workbook">工作薄</param>
        /// <returns></returns>
        public static byte[] SaveToBuffer(this IWorkbook workbook)
        {
            using (var ms = new MemoryStream())
            {
                workbook.Write(ms);
                return ms.ToArray();
            }
        }

        #endregion

    
    }


}
